<template>
  <el-dialog
    :visible.sync="dialogVisible"
    title="对比分析"
    append-to-body
    width="1000px"
    class="eldialog"
  >
    <div id="contrastiveChart" class="chart"></div>
  </el-dialog>
</template>

<script>
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt } from "@/utils/utils";
import {
  refactor,
  getYear,
  transCNCountry,
  downloadChartImg,
} from "@/utils/utils";
export default {
  data() {
    return {
      chart: null,
      colors: [],
      chartData: [],
      xData: [],
      yData: [],
      legendData: [],
      dialogVisible: false,

      dbid: "",
      timeType: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "",
      msq: "",
      filedArr: [],
    };
  },
  methods: {
    init(data, chartTempl, dbid, _sq) {
      this.filedArr = [];
      data.map((item) => {
        this.filedArr.push(item.name);
      });
      this.msq = _sq;
      this.dbid = dbid;
      this.loading = false;
      console.log("chartTempl", chartTempl);
      this.getChartData(chartTempl);
    },
    getChartData(chartTempl) {
      this.loading = true;
      let _field = chartTempl.tdata.param.aggs[0].field;
      let _datefield = chartTempl.tdata.datefield;
      // let sq = `${this.timeType}>=${this.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${this.endYear}${this.datefieldformatTxt}`
      let sq = this.msq;
      let _str = "";
      this.filedArr.map((item) => {
        _str = _str + " OR " + _field + "==" + item;
      });
      sq = sq + " AND (" + _str + ")";
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: [],
      };
      let params = {
        aggs: [{ field: _field, aggs: [{ field: _datefield }] }],
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 0,
        rSearch: "",
        smartSearch: "",
        sort: [],
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      this.$post(this.$Url.search.commonSearch, params)
        .then((res) => {
          let data = JSON.parse(JSON.stringify(res.data.chartData));
          this.loading = false;
          data.forEach((v) => {
            v.key = transCNCountry(v.key);
          });
          refactor({
            type: 0, // 根据后台返回的datatype，判断数据解析格式
            data,
            callback: (refactor) => {
              let arr = []
              refactor.data[0].map(item => {
                arr.push(item.split('-')[0])
              })
              refactor.data[0] = arr
              this.chartData = refactor.data;
            },
          });
          this.drawCharts();
          this.loading = false;
        })
        .catch((err) => {
          this.emptyText = "暂无数据";
          this.loading = false;
        });
    },

    getSeriesData() {
      let seriesData = [];
      for (let i = 0; i < this.chartData.length; i++) {
        if (this.chartData[i][0] !== "product") {
          let obj = {
            type: "line",
            name: this.chartData[i][0],
            seriesLayoutBy: "row",
            symbol: "circle",
            symbolSize: "8",
            connectNulls: true,
            smooth: true,
            scale: true,
            barMaxWidth: 16,
            connectNulls: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#6b6c7e",
                fontSize: 12,
              },
            },
          };
          if (this.needStack) {
            obj["stack"] = "all";
          }
          seriesData.push(obj);
        }
      }
      return seriesData;
    },
    drawCharts() {
      let seriesData = this.getSeriesData();
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.chart = this.$echarts.init(
          document.getElementById("contrastiveChart")
        );
        this.renderChart(seriesData);
      });
    },
    renderChart(seriesData) {
      let option = {
        legend: {
          show: true,
        },
        dataset: {
          source: JSON.parse(JSON.stringify(this.chartData)),
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
          // 轴线
          axisLabel: {
            rotate: 40,
            interval: 0,
            margin: 10,
            textStyle: {
              color: "#9e9e9e",
            },
            formatter: (label) => {
              return spaceTxt(label, 10);
            },
          },
        },
        yAxis: {
          type: "value",
          minInterval: 1,
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#f0f1f3",
              width: 2,
            },
          },
          axisLabel: {
            textStyle: {
              color: "#9e9e9e",
            },
          },
        },
        series: seriesData,
      };
      this.chart.clear();
      this.chart.setOption(option);
    },
  },
  mounted() {},
  destroyed() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
};
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 40vh;
  max-height: 500px;
}
</style>